<template>
  <div class="commoditySpecifications-container">
    <el-form :model="formData" v-for="(item, index) in specArr" :key="index">
      <el-form-item label="规格名：" prop="CSName">
        <el-input
          v-model="item.text"
          size="large"
          class="CSName-class"
          @change="sectionTitleChange(item, index)"
        ></el-input>
      </el-form-item>
      <el-form-item label="规格值：" prop="value">
        <div class="value">
          <el-input
            v-for="(e, jindex) in item.value"
            :key="jindex"
            size="large"
            v-model="e.value"
            @change="valueChange(index, jindex, e)"
          >
            <template #append>
              <el-button type="text" @click="deleteFunc(index, jindex, e)">
                删除
              </el-button>
            </template>
          </el-input>
          <el-button type="text" @click="add(item, index)">
            添加规格值
          </el-button>
        </div>
      </el-form-item>
    </el-form>
    <el-button v-if="specArr.length <= 3" class="add-btn" @click="addSection">
      添加规格
    </el-button>
  </div>
</template>
<script lang="ts" setup>
  // TODO 上级为空不能添加，下级还有不能删完
  // 没有添加section 不能添加内容
  import { ref, computed, watch, Ref } from 'vue'
  import { buildUUID } from '@/utils/uuid'
  import { specValue } from '@/types/shop'
  import common from '@/utils/common'
  import { cloneDeep } from 'lodash'
  const formData = ref({})

  const props = defineProps({
    initData: {
      type: Array,
      default() {
        return []
      },
    },
  })

  const newSectionIndex = ref(0)
  const emits = defineEmits([
    'addSpec',
    'editSpec',
    'deteleCell',
    'sectionTitleChange',
  ])

  const specArr: any = computed(() => {
    const arr = props.initData.filter((item: any, index: number) => {
      return index + 1 <= newSectionIndex.value || item.value.length !== 0
    })
    return arr
  })
  // const specArr = ref([]) as Ref<any>
  watch(
    () => props.initData,
    () => {
      if (newSectionIndex.value > 0) return
      newSectionIndex.value = props.initData.filter(
        (item: any, index: number) => {
          return item.value.length !== 0
        }
      ).length
    },
    { deep: true, immediate: true }
  )
  const oldSpecArr = ref({})
  // 更新本地缓存数据
  function updataOldSepcArr(specArr: any) {
    oldSpecArr.value = cloneDeep(specArr.value)
  }

  function deleteFunc(index: number, jindex: number, e: specValue) {
    const tmpArr = cloneDeep(specArr.value[index].value)
    tmpArr.splice(jindex, 1)

    if (tmpArr && tmpArr.length < 1) newSectionIndex.value -= 1

    specArr.value[index].value = tmpArr
    updataOldSepcArr(specArr)

    emits('deteleCell', {
      sectionIndex: index,
      cellIndex: jindex,
      text: e.value,
    })
  }

  function add(item: any, index: number) {
    // 还未添加 所以不是减一
    const jindex = specArr.value[index].value.length
    if (jindex !== 0) {
      const beforeIndex = jindex - 1
      const tmp = specArr.value[index].value[beforeIndex].value
      if (!tmp) {
        common.XmMessage(1, '请补完上方空白再填入')
        return
      }
    }
    item.value.push({ value: null })
    updataOldSepcArr(specArr)
  }
  // 值的修改
  function valueChange(index: number, jindex: number, item: any) {
    // 防止修改为空
    if (!specArr.value[index].value[jindex].value) {
      common.XmMessage(1, '不能为空，如不需要可删除')
      specArr.value[index].value[jindex].value =
        // @ts-ignore
        oldSpecArr.value[index].value[jindex].value
      return
    }
    if (specArr.value.length > index) {
      const values = specArr.value[index].value
      const text = specArr.value[index].text
      const b = !!values.find(
        (e: specValue, eindex: number) =>
          e.value === item.value && eindex !== jindex
      )
      if (b) {
        common.XmMessage(1, '同规格下，已有相同规格值')
        specArr.value[index].value[jindex].value = ''
        return
      }

      if (item.uuid) {
        // 修改
        console.log('修改 = ' + JSON.stringify(item))
        editSpec(index, item, text)
      } else {
        // 新增
        item.uuid = buildUUID()
        console.log('新增 = ' + JSON.stringify(item))
        addSpec(index, item, text)
      }
      updataOldSepcArr(specArr)
    }
  }

  // 输出字段
  function getvalue() {
    return specArr.value
  }

  function addSpec(index: number, value: Object, sectionTitle: string) {
    emits('addSpec', { index, value, sectionTitle })
  }
  function editSpec(index: number, value: Object, sectionTitle: string) {
    emits('editSpec', { index, value, sectionTitle })
  }
  function addSection() {
    if (newSectionIndex.value < 3) {
      if (newSectionIndex.value !== 0) {
        const isSpecArrHas = specArr.value.length > 0
        const text = isSpecArrHas
          ? specArr.value[newSectionIndex.value - 1].text
          : ''
        const value = isSpecArrHas
          ? specArr.value[newSectionIndex.value - 1].value
          : []
        if (!text && isSpecArrHas) {
          common.XmMessage(1, '请补完上方空白再填入')
          return
        } else if ((value.length <= 0 || !value[0].value) && isSpecArrHas) {
          common.XmMessage(1, '请补充上方规格再填入')
          return
        }
      }
      newSectionIndex.value += 1
    }
  }

  function sectionTitleChange(item: any, index: number) {
    // 防止修改为空
    if (!specArr.value[index].text) {
      common.XmMessage(1, '不能为空，如不需要可删除')
      specArr.value[index].text =
        // @ts-ignore
        oldSpecArr.value[index].text
      return
    }
    if (specArr.value.length > index) {
      const values = specArr.value[index].value
      const text = specArr.value[index].text
      const b = !!specArr.value.find((e: any, eindex: number) => {
        return e.text === item.text && eindex !== index
      })
      if (b) {
        common.XmMessage(1, '同规格下，已有相同规格值')
        specArr.value[index].text = ''
        return
      }
    }

    emits('sectionTitleChange', { text: item.text, index })
    updataOldSepcArr(specArr)
  }

  // 提交给外部使用
  defineExpose({ getvalue })
</script>
<style lang="scss" scoped>
  .commoditySpecifications-container {
    display: flex;
    flex-direction: column;
    .el-form {
      margin-bottom: 10px;
      .el-input {
        margin-right: 10px;
      }
    }
    .value {
      display: flex;
    }
    .CSName-class {
      margin-bottom: 10px;
      width: 400px;
    }
    .add-btn {
      // margin-top: 10px;
      margin-left: 70px;
      width: 200px;
    }
  }
</style>
